<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017-08-16
 * Time: 23:22
 */

namespace app\commands;
use yii\console\Controller;

class ScheduleController
{
    /**
     * 删除该路径下的临时文件
     * yii hello/delete-temp-file
     */
    public function actionDeleteTempFile()
    {
        $temp_path = \Yii::$app->basePath . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'upload';
        $dirs = array();
        if (is_dir($temp_path)) {
            if ($dh = opendir($temp_path)) {
                $i = 0;
                while (($dir = readdir($dh)) !== false) {
                    if ($dir != '.' && $dir != '..') {
                        if (is_dir($temp_path . DIRECTORY_SEPARATOR . $dir)) {

                            $dirs[$i] = $temp_path . DIRECTORY_SEPARATOR . $dir;
                            $i++;
                        }
                    }
                }

                closedir($dh);
            }
        }

        //删除文件夹
        for ($i = 0; $i < count($dirs); $i++) {
            $dir = $dirs[$i];
            $dir_name = basename($dir);
            if ($dir_name < date('Ymd')) {
                self::_deleteDir($dir);
            }
        }
    }

    /**
     * 删除文件夹(包括子文件夹及文件)
     * @param $dir
     */
    private function _deleteDir($dir)
    {
        if (is_dir($dir)) {
            $handle = dir($dir);
            while (false !== ($entry = $handle->read())) {
                if (($entry != '.' && $entry != '..')) {
                    if (is_file($dir . DIRECTORY_SEPARATOR . $entry)) {
                        unlink($dir . DIRECTORY_SEPARATOR . $entry);
                    } else {
                        self::_deleteDir($dir . DIRECTORY_SEPARATOR . $entry);
                    }
                }
            }
            $handle->close();
            rmdir($dir);
        }
    }
}